<?php

namespace Api\Controller;

use Common\Controller;
use Common\Utils\validate\Validate;

class UserCenterController extends Controller\ApiController {

    private $couponListModel;
    private $userModel;
    private $userDefaultAvatarModel;
    private $userBusinessDistrictModel;
    private $userCategoryModel;
    private $userLikeShopModel;

    public function __construct() {
        $this->couponListModel = D('CouponList');
        $this->userModel = D('User');
        $this->userDefaultAvatarModel = D('UserDefaultAvatar');
        $this->userBusinessDistrictModel = D('UserBusinessDistrict');
        $this->userCategoryModel = D('UserCategory');
        $this->userLikeShopModel = D('UserLikeShop');
    }

    /**
     * @name 获取用户优惠券
     * @param $longitude 经度
     * @param $latitude 纬度
     * @param $num  每页显示数量
     * @param $page 页码
     */
    public function getCoupon() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $longitude = getParameter('longitude');
        $latitude = getParameter('latitude');
        $page = getParameter('page');
        $num = getParameter('num');
        $params = array(
            array('key' => 'longitude', 'val' => $longitude, 'require' => true, 'msg' => '缺少经度参数！'),
            array('key' => 'latitude', 'val' => $latitude, 'require' => true, 'msg' => '缺少纬度参数！'),
            array('key' => 'page', 'val' => $page, 'require' => true, type => 'pint', 'msg' => '页码不正确！'),
            array('key' => 'num', 'val' => $num, 'require' => true, type => 'pint', 'msg' => '数目参数不正确！')
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.获取用户优惠券
        $userInfo = $this->getUserInfo();
        $data = $this->couponListModel->getCoupon($userInfo['user_id'], $longitude, $latitude, $num, $page);
        $this->output($data);
    }

    /**
     * @name 获取用户详情
     */
    public function getUserDetail() {
        //1.验证是否登陆
        parent::auth();
        //2.获取用户详情
        $userInfo = $this->getUserInfo();
        $data = $this->userModel->getUserDetail($userInfo['user_id']);
        $this->output($data);
    }

    /**
     * @name 发布时获取优惠券详情
     * @param $coupon_code
     */
    public function getPublishCouponInfo() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');
        $longitude = getParameter('longitude');
        $latitude = getParameter('latitude');
        $params = array(
            array('key' => 'longitude', 'val' => $longitude, 'require' => true, 'msg' => '缺少经度参数！'),
            array('key' => 'latitude', 'val' => $latitude, 'require' => true, 'msg' => '缺少纬度参数！'),
            array('key' => 'coupon_code', 'val' => $couponCode, 'require' => true, 'msg' => '优惠券不存在！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }

        //3.获取优惠券详情
        $userInfo = $this->getUserInfo();
        $data = $this->couponListModel->getPublishCouponInfo($userInfo['user_id'], $couponCode, $longitude, $latitude);
        if ($data == false) {
            $this->error('优惠券不存在！');
        } else {
            $this->output($data);
        }
    }

    /**
     * @name 发布优惠券
     * @param $coupon_id 优惠券码
     */
    public function publishCoupon() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');
        $remark = getParameter('remark', false);
        $params = array(
            array('key' => 'coupon_code', 'val' => $couponCode, 'require' => true, 'msg' => '优惠券不存在！'),
            array('key' => 'remark', 'val' => $remark, 'require' => false)
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.发布优惠券
        $userInfo = $this->getUserInfo();
        $result = $this->couponListModel->publishCoupon($userInfo['user_id'], $couponCode, $remark);
        if ($result['status'] == 1) {
            $this->success($result['msg']);
        } else {
            $this->error($result['msg']);
        }
    }

    /**
     * 获取系统消息
     */
    function getSystemMsg() {
        $user_info = $this->auth();

        $page = (int) I('page');
        $no = (int) I('no');
        $no = $no == 0 || $no > 20 ? 10 : $no;
        $model = M('MsgOutbox')->alias('o');
        $where = array();
        $where['o.user_id'] = array(array('eq', 0), array('eq', $user_info['user_id']), 'or');
        $where['i.read_id'] = array('exp', 'is null');
        $sql = M('MsgInbox')->where(array('read_id' => $user_info['user_id'], 'type' => '2'))->select(false); //已删除的不需要
        $list = $model->page($page, $no)->field('o.content,o.create_time,o.id')->where($where)->join("($sql) as i ON i.outbox_id=o.id", 'left')->order('id desc')->select();
        $this->output($list);
    }

    /**
     * 删除系统消息
     */
    function delSystemMsg() {
        $user_info = $this->auth();
        $msg_id = I('id');
        $time = time();
        $model = M('MsgInbox');
        $msg_id = explode(',', trim($msg_id, ','));
        $data = array(
            'read_id' => $user_info['user_id'],
            'type' => '2',
            'create_time' => $time,
        );
        $where = array();
        $where['id'] = array('in', $msg_id);
        $where['user_id'] = array(array('eq', 0), array('eq', $user_info['user_id']), 'or');
        $msg_count = M('MsgOutbox')->where($where)->count();
        if ($msg_count != count($msg_id))//如果传入的ID数量和应有的消息数量不等 就报错(验证传入的消息都是输入该用户的消息)
            $this->error('删除失败');
        foreach ($msg_id as $id) {
            $data['outbox_id'] = $id;
            $model->add($data, '', true);
        }
        $this->success();
    }

    /**
     * @name 获取默认头像
     */
    public function getDefaultAvatar() {
        //1.验证是否登陆
        parent::auth();
        //2.获取默认头像
        $data = $this->userDefaultAvatarModel->getDefaultAvatar();
        $this->output($data);
    }

    /**
     * @name 保存默认头像
     * @param $id
     */
    public function saveDefaultAvatar() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $id = getParameter('id');
        $params = array(
            array('key' => 'id', 'val' => $id, 'require' => true, 'type' => 'pint', 'msg' => ' 请选择头像！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.保存默认头像
        $userInfo = $this->getUserInfo();
        $result = $this->userDefaultAvatarModel->saveDefaultAvatar($userInfo['user_id'], $id);
        if (!$result)
            $this->error(D('UserDefaultAvatar')->last_msg());
        $this->success('设置头像成功！');
    }

    /**
     * @name 删除优惠券
     */
    public function deleteCoupon() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');
        $params = array(
            array('key' => 'coupon_code', 'val' => $couponCode, 'require' => true, 'msg' => ' 优惠券不存在！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.删除优惠券
        $userInfo = $this->getUserInfo();
        $result = $this->couponListModel->deleteCoupon($userInfo['user_id'], $couponCode);
        if (!$result)
            $this->error(D('CouponList')->last_msg());
        $this->success('删除成功！');
    }

    /**
     * @name 取消发布优惠券
     */
    public function cancelPublishCoupon() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');
        $params = array(
            array('key' => 'coupon_code', 'val' => $couponCode, 'require' => true, 'msg' => ' 优惠券不存在！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.取消发布优惠券
        $userInfo = $this->getUserInfo();
        $result = $this->couponListModel->cancelPublishCoupon($userInfo['user_id'], $couponCode);
        if (!$result)
            $this->error(D('CouponList')->last_msg());
        $this->success('取消成功！');
    }

    public function getCreditMsg() {
        $user_info = $this->auth();
        $page = (int) I('page');
        $no = (int) I('no');
        $no = $no == 0 || $no > 20 ? 10 : $no;
        $model = M('CreditLog');
        $where = array();
        $where['user_id'] = $user_info['user_id'];
        $list = $model->where($where)->page($page, $no)->order('id desc')->field('create_time,name,id')->select();
        $this->output($list);
    }

    function delCreditMsg() {
        $user_info = $this->auth();
        $msg_id = I('id');
        $model = M('CreditLog');
        $msg_id = explode(',', trim($msg_id, ','));

        if (emptys($msg_id))
            $this->error('删除失败,请重试');

        $where = array();
        $where['id'] = array('in', $msg_id);
        $where['user_id'] = $user_info['user_id'];
        $result = $model->where($where)->delete();
        if (!$result)
            $this->error('删除失败,请重试');
        else
            $this->success();
    }

    /**
     * @name 保存昵称
     */
    public function saveNickname() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $nickname = getParameter('nickname');
        $params = array(
            array('key' => 'nickname', 'val' => $nickname, 'require' => true, 'type' => 'length', 'min' => 4, 'max' => 16, 'msg' => '昵称格式不正确,请填写4至16个字符！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.保存昵称
        $userInfo = $this->getUserInfo();
        $result = $this->userModel->saveNickname($userInfo['user_id'], $nickname);
        if ($result) {
            $this->success('保存成功！');
        } else {
            $this->error('保存失败！');
        }
    }

    /**
     * @name 获取用户商区
     */
    public function getUserBusinessDistrict() {
        //1.验证是否登陆
        parent::auth();
        //2.获取用户商区
        $userInfo = $this->getUserInfo();
        $result = $this->userBusinessDistrictModel->getUserBusinessDistrict($userInfo['user_id']);
        $this->output($result);
    }

    /**
     * @name 获取用户喜好
     */
    public function getUserCategory() {
        //1.验证是否登陆
        parent::auth();
        //2.获取用户商区
        $userInfo = $this->getUserInfo();
        $result = $this->userCategoryModel->getUserCategory($userInfo['user_id']);
        $this->output($result);
    }

    /**
     * @name 获取喜欢的商家
     */
    public function getFavoriteBusiness() {
        //1.验证是否登陆
        parent::auth();
        //2.获取用户商区
        $userInfo = $this->getUserInfo();
        $result = $this->userLikeShopModel->getFavoriteBusiness($userInfo['user_id']);
        $this->output($result);
    }

    /**
     * @name 获取优惠券使用地址
     */
    public function getUseCouponLink() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');
        $params = array(
            array('key' => 'coupon_code', 'val' => $couponCode, 'require' => true, 'msg' => ' 优惠券不存在！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.输出优惠券使用地址
        $link = '/UserCenter/useCoupon/coupon_code/' . $couponCode;
        $this->output(array('link' => $link));
    }

    /**
     * @name 使用优惠券
     */
    public function useCoupon() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');
        $params = array(
            array('key' => 'coupon_code', 'val' => $couponCode, 'require' => true, 'msg' => ' 优惠券不存在！'),
        );
        $msg = Validate::checkParams($params);
        if ($msg) {
            $this->error($msg[0]);
        }
        //3.使用优惠券
        $userInfo = $this->getUserInfo();
        $result = $this->couponListModel->useCoupon($userInfo['user_id'], $couponCode);
        if (!$result)
            $this->error(D('CouponList')->last_msg());
        $this->success('使用成功！');
    }

    public function uploadAvatar() {
        $user_info = $this->auth();
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = 500 * 1000; // 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
        $USER_UPLOAD_AVATAR = C('USER_UPLOAD_AVATAR');
        $upload->rootPath = $USER_UPLOAD_AVATAR; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件 
        $info = $upload->upload($_FILES);
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }
        $info = $info['avatar'];
        $user_info = $this->getUserInfo();
        $user_avatar = trim($USER_UPLOAD_AVATAR, '.') . $info['savepath'] . $info['savename'];
        $this->userModel->save(array('id' => $user_info['user_id'], 'avatar' => $user_avatar));
        $this->output(array('avatar' => $user_avatar));
    }

}
